package com.g4.shoppingsingle.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.g4.shoppingsingle.exception.ServiceException;
import com.g4.shoppingsingle.mapper.DdUsersInfoMapper;
import com.g4.shoppingsingle.mapper.UserRoleMapper;
import com.g4.shoppingsingle.model.DdUsersInfo;
import com.g4.shoppingsingle.model.Permission;
import com.g4.shoppingsingle.model.Role;
import com.g4.shoppingsingle.model.UserRole;
import com.g4.shoppingsingle.service.IDdUsersInfoService;
import com.g4.shoppingsingle.vo.RegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-10-27
 */
@Slf4j
@Service
public class DdUsersInfoServiceImpl extends ServiceImpl<DdUsersInfoMapper, DdUsersInfo>
        implements IDdUsersInfoService, UserDetailsService {
    //用户表的持久层
    @Autowired
    private DdUsersInfoMapper ddUsersInfoMapper;

    //用户角色关系表
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 业务逻辑层
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public DdUsersInfo getMyInfo(Integer userId) {
        //调用持久层,通过用户id去数据库查询用户信息
        DdUsersInfo ddUsersInfo = ddUsersInfoMapper.selectById(userId);
        return ddUsersInfo;
    }

    @Override
    public void registerUser(RegisterVo registerVo) {

        //根据用户输入的手机号,获得用户信息
        DdUsersInfo ddUsersInfo = ddUsersInfoMapper.findUserByTelephone(registerVo.getTelephone());
        //如果能够获得用户信息,表示当前手机号已经被注册
        if (ddUsersInfo != null) {
            throw new ServiceException("手机号已经被注册!");
        }
        //对用户输入的密码进行加密
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = "{bcrypt}"+encoder.encode(registerVo.getPassword());
        DdUsersInfo usersInfo = new DdUsersInfo()
                .setUserName(registerVo.getUserName())
                .setPassword(pwd)
                .setTelephone(registerVo.getTelephone())
                .setCreateTime(LocalDateTime.now())
                .setAge(18)
                .setGender(1)
                .setSign(registerVo.getSign())
                .setHobby(registerVo.getHobby())
                .setAddress(registerVo.getAddress());
        int num = ddUsersInfoMapper.insert(usersInfo);
        //获取数据库生成的用户id
        Integer userId = usersInfo.getId();

        //给注册的用户分配一个默认的角色
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        System.out.println("用户id是：" + userId);
        userRole.setRoleId(2);
        int flag = userRoleMapper.insert(userRole);

        if (num != 1 || flag != 1) {
            throw new ServiceException("数据库忙~~~~~");
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("进来了");
        // 1.根据用户名查询用户对象(手机号)
        DdUsersInfo user = ddUsersInfoMapper.findUserByUserName(username);
        // 2.判断是否能够查询到用户,没有该用户表示用户名不存在
        if (user == null) {
            return null;
        }
        // 3.根据用户id查询用户的所有权限
        List<Permission> permissions = ddUsersInfoMapper
                .findUserPermissionsById(user.getId());
        // 4.将权限的集合转换为String类型数组,并赋值
        String[] auth = new String[permissions.size()];
        int i = 0;
        for (Permission p : permissions) {
            auth[i] = p.getName();
            i++;
        }
        // 查询当前用户所有角色
        List<Role> roles = ddUsersInfoMapper.findUserRolesById(
                user.getId());
        // 数组扩容
        auth = Arrays.copyOf(auth,
                auth.length + roles.size());
        //  {"/getid","/add","/update","/upload",null}
        for (Role role : roles) {
            auth[i++] = role.getName();
        }
        // 5.构建UserDetails对象
        UserDetails details = org.springframework.security
                .core.userdetails.User.builder()
                .username(user.getUserName())
                .password(user.getPassword())
                .authorities(auth)
//                //设置当前账户是否锁定 false表示不锁定
//                .accountLocked(user.get()==1)
//                //设置当前账户是否可用 false表示可用
//                .disabled(user.getEnabled()==0)
                .build();
        // 6.返回UserDetails对象
        log.debug("用户信息详情--:" + details);
        return details;
    }
}
